package john.walker.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import john.walker.log.ConsoleLogger;
import john.walker.log.ILog;
import john.walker.log.LogFactory;
import john.walker.log.MultiLogger;

/**
 * @author 30san
 *
 */
public class ConfigLoader {

	private static Properties prop = new Properties();

	private ConfigLoader () {

	}

	static {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		InputStream in = loader.getResourceAsStream("dbProxy.properties");
		if(in != null) {
			try {
				prop.load(in);
				in.close();
			} catch (IOException e) {
				StringWriter writer = new StringWriter();
				e.printStackTrace(new PrintWriter(writer));
				LogFactory.getLogger().log(writer.toString());
			}
		}
	}

	/**
	 * 加载过滤器
	 *
	 * @return
	 */
	public static List<String> loadFilterWords() {
		List<String> words = new ArrayList<String>();
		Set<Object> keys = prop.keySet();
		for(Object key : keys) {
			if(key.toString().startsWith("word")) {
				words.add(prop.getProperty(key.toString()));
			}
		}
		return words;
	}

	/**
	 * 加载日志组件
	 */
	public static void loadLoggers() {
		Set<Object> keys = prop.keySet();
		MultiLogger mutiLogger = new MultiLogger();
		boolean hasOne = false;
		for(Object key : keys) {
			if(key.toString().startsWith("logger")) {
				String loggerClassName = prop.getProperty(key.toString());
				try {
					ILog logger = (ILog) Class.forName(loggerClassName).newInstance();
					mutiLogger.addLogger(logger);
					hasOne = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if(!hasOne) {
			LogFactory.setLogger(new ConsoleLogger());
		} else {
			LogFactory.setLogger(mutiLogger);
		}
	}


	/**
	 * sql 监控开关
	 *
	 * @return
	 */
	public static boolean sqlMonitor() {
		Object obj = prop.get("sql_monitor");
		if(obj == null) {
			return false;
		}

		return Boolean.valueOf(obj.toString());
	}


	/**
	 * 连接监控开关
	 *
	 * @return
	 */
	public static boolean connectionMonitor() {
		Object obj = prop.get("connection_monitor");
		if(obj == null) {
			return false;
		}

		return Boolean.valueOf(obj.toString());
	}


	/**
	 * sql监控调用栈开关
	 *
	 * @return
	 */
	public static boolean sqlMonitorStack() {
		Object obj = prop.get("sql_monitor_stack");
		if(obj == null) {
			return false;
		}

		return Boolean.valueOf(obj.toString());
	}

	/**
	 * sql监控时间
	 *
	 * @return
	 */
	public static long sqlMonitorTime() {
		Object obj = prop.get("sql_monitor_time");
		if(obj == null) {
			return 0;
		} else {
			try {
				return Long.valueOf(obj.toString());
			} catch (Exception e) {
				return 0;
			}
		}
	}
}
